/**
 * 
 */
package com.csc.bankingsystem.web.spring.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.csc.bankingsystem.core.dto.BSAuthReturnObject;
import com.csc.bankingsystem.web.exception.BSBadCredentialsException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author angelkid
 *
 */
public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	
	private final ObjectMapper mapper;

	@Autowired
	AuthFailureHandler(MappingJackson2HttpMessageConverter messageConverter) {
		this.mapper = messageConverter.getObjectMapper();
	}
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		PrintWriter writer = response.getWriter();
		if(exception instanceof BSBadCredentialsException){
			BSBadCredentialsException bsBadCredentialsException = (BSBadCredentialsException) exception;
			BSAuthReturnObject returnObj = new BSAuthReturnObject();
			returnObj.setErrorCode(bsBadCredentialsException.getErrorCode());
			returnObj.setErrorMsg(bsBadCredentialsException.getErrorMsg());
			mapper.writeValue(writer, returnObj);
		} else{
			writer.write(exception.getMessage());
		}
		writer.flush();
	}
}
